package com.kinsin.kinsinutil

import org.junit.Assert
import org.junit.Test

class CryptoUtilsTest {

    // region 哈希算法测试
    @Test
    fun testMd5() {
        val input = "hello"
        val expected = "5d41402abc4b2a76b9719d911017c592" // 已知MD5结果
        Assert.assertEquals(expected, CryptoUtils.md5(input))
    }

    @Test
    fun testSha256() {
        val input = "kotlin"
        val expected = "19a67c2a53695668e4916e9e64cf0613352ec614fd682a8bf8bf98a471db5e8d" // 实际结果需替换
        Assert.assertEquals(expected, CryptoUtils.sha256(input))
    }
    // endregion

    // region 加盐哈希测试
    @Test
    fun testMd5WithSalt_SameSaltSameResult() {
        val input = "password123"
        val salt = CryptoUtils.generateSalt()

        val hash1 = CryptoUtils.md5WithSalt(input, salt)
        val hash2 = CryptoUtils.md5WithSalt(input, salt) // 相同盐应结果一致

        Assert.assertEquals(hash1, hash2)
    }

    @Test
    fun testMd5WithSalt_DifferentSaltDifferentResult() {
        val input = "password123"
        val salt1 = CryptoUtils.generateSalt()
        val salt2 = CryptoUtils.generateSalt()

        val hash1 = CryptoUtils.md5WithSalt(input, salt1)
        val hash2 = CryptoUtils.md5WithSalt(input, salt2) // 不同盐应结果不同

        Assert.assertNotEquals(hash1, hash2)
    }
    // endregion

    // region AES 加解密测试
    @Test
    fun testAES_EncryptDecryptSuccess() {
        val originalText = "TopSecretMessage123"
        val key = CryptoUtils.generateAESKey()

        val encrypted = CryptoUtils.encryptAES(originalText, key)
        val decrypted = CryptoUtils.decryptAES(encrypted, key)

        Assert.assertEquals(originalText, decrypted)
    }

    @Test
    fun testAES_DifferentKeyDecryptFail() {
        val originalText = "HelloAES"
        val key1 = CryptoUtils.generateAESKey()
        val key2 = CryptoUtils.generateAESKey() // 不同密钥

        val encrypted = CryptoUtils.encryptAES(originalText, key1)
        val decrypted = try {
            CryptoUtils.decryptAES(encrypted, key2) // 应抛出异常或乱码
            "DecryptedWithWrongKey"
        } catch (e: Exception) {
            "DecryptFailed"
        }

        Assert.assertNotEquals(originalText, decrypted)
    }
    // endregion

    // region Base64 测试
    @Test
    fun testBase64_EncodeDecode() {
        val original = "Base64TestData"
        val encoded = CryptoUtils.encodeBase64(original.toByteArray())
        val decoded = String(CryptoUtils.decodeBase64(encoded))

        Assert.assertEquals(original, decoded)
    }
    // endregion

    // region 盐生成测试
    @Test
    fun testGenerateSalt_LengthAndRandomness() {
        val salt1 = CryptoUtils.generateSalt()
        val salt2 = CryptoUtils.generateSalt() // 两次生成的盐应不同

        Assert.assertEquals(16, salt1.size) // 默认长度16
        Assert.assertFalse(salt1.contentEquals(salt2))
    }
    // endregion
}